import React, { FC, useState, useEffect, createElement } from 'react';
import {
  Divider,
  Comment,
  Avatar,
  Form,
  Button,
  List,
  Input,
  Typography,
  Space,
  Tooltip,
  Pagination,
} from 'antd';
import styles from './comment.less';
import moment from 'moment';
import { connect, CommentModelState, ConnectProps } from 'umi';
import { parseTime } from '@/utils';
import {
  DislikeOutlined,
  LikeOutlined,
  DislikeFilled,
  LikeFilled,
} from '@ant-design/icons';

interface PageProps extends ConnectProps {
  commentModel: CommentModelState;
  dispatch: any;
}

const { Text } = Typography;
const { TextArea } = Input;

const CommentCompoment: FC<PageProps> = ({
  commentModel,
  dispatch,
  id,
  type,
}: any) => {
  let submitting: boolean = false;
  let value: string = '';
  let dataSourceList: any = [];
  const [offset, setOffset] = useState(1);
  const [limit, setLimit] = useState(10);

  useEffect(() => {
    if (id) {
      setOffset(1);
      setLimit(10);
      dataSource();
    }
  }, [id]);

  let dataSource = () => {
    dispatch({
      type: 'commentModel/getListData',
      payload: {
        id: id,
        type: type,
        offset: 1,
        limit: 10,
      },
    });
  };

  const [likes, setLikes] = useState(0);
  const [dislikes, setDislikes] = useState(0);
  const [action, setAction] = useState(null);

  const like = () => {
    setLikes(1);
    setDislikes(0);
    setAction('liked');
  };

  const dislike = () => {
    setLikes(0);
    setDislikes(1);
    setAction('disliked');
  };

  commentModel.commentList.forEach((item: any, index: number) => {
    let obj = {
      actions: [
        <span key="comment-basic-like">
          <Tooltip title="Like">
            {createElement(action === 'liked' ? LikeFilled : LikeOutlined, {
              onClick: like,
            })}
          </Tooltip>
          <span className="comment-action">{likes}</span>
        </span>,
        <span key="comment-basic-dislike">
          <Tooltip title="Dislike">
            {React.createElement(
              action === 'disliked' ? DislikeFilled : DislikeOutlined,
              {
                onClick: dislike,
              },
            )}
          </Tooltip>
          <span className="comment-action">{dislikes}</span>
        </span>,
        <span key="comment-list-reply-to-0">回复</span>,
      ],
      author: item.user.nickname,
      avatar: item.user.avatarUrl,
      content: <p>{item.content}</p>,
      datetime: parseTime(item.time, '{y}-{m}-{d}'),
    };
    dataSourceList.push(obj);
  });

  const Editor = ({ onChange, onSubmit, submitting, value }: any) => (
    <>
      <Form.Item>
        <TextArea rows={4} onChange={onChange} maxLength={140} />
      </Form.Item>
      <Form.Item>
        <div className={styles.textRight}>
          <Space size={15}>
            <Text>{value.length} / 140</Text>
            <Button
              htmlType="submit"
              loading={submitting}
              onClick={onSubmit}
              type="primary"
            >
              评论
            </Button>
          </Space>
        </div>
      </Form.Item>
    </>
  );

  const handleChange = (e: any) => {
    //setValue(e.target.value)
    value = e.target.value;
    console.log(value);
  };

  const handleSubmit = (e: any) => {
    console.log(value);
    if (!value) {
      return;
    }
    submitting = true;
  };

  const changePagination = (page: number) => {
    setOffset(page);
    dispatch({
      type: 'commentModel/getListData',
      payload: {
        id: id,
        type: type,
        offset: page,
        limit: limit,
      },
    });
  };
  const changeSize = (current: number, size: number) => {
    setLimit(size);
    dispatch({
      type: 'commentModel/getListData',
      payload: {
        id: id,
        type: type,
        offset: offset,
        limit: size,
      },
    });
  };

  return (
    <div className={styles.comment}>
      <Divider orientation="left">评论</Divider>

      {/*评论操作*/}
      <Comment
        avatar={
          <Avatar
            src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"
            alt="Han Solo"
          />
        }
        content={
          <Editor
            onChange={handleChange}
            onSubmit={handleSubmit}
            submitting={submitting}
            value={value}
          />
        }
      />

      {/*评论列表*/}
      <List
        className="comment-list"
        itemLayout="horizontal"
        dataSource={dataSourceList}
        renderItem={(item: any) => (
          <li>
            <Comment
              actions={item.actions}
              author={item.author}
              avatar={item.avatar}
              content={item.content}
              datetime={item.datetime}
            />
          </li>
        )}
      />

      <div className={styles.center}>
        <Pagination
          total={commentModel.total}
          showTotal={(total, range) =>
            `${range[0]}-${range[1]} of ${total} items`
          }
          onChange={page => {
            changePagination(page);
          }}
          onShowSizeChange={(current, size) => {
            changeSize(current, size);
          }}
          defaultPageSize={10}
          current={offset}
        />
      </div>
    </div>
  );
};

export default connect(
  ({ commentModel }: { commentModel: CommentModelState }) => ({ commentModel }),
)(CommentCompoment);
